package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.DepartmentOrUserSimpleDTO;
import com.nineclock.system.dto.SysDepartmentDTO;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysDepartmentMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysDepartment;
import com.nineclock.system.service.SysDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysDepartmentServiceImpl implements SysDepartmentService {

    @Autowired
    private SysDepartmentMapper departmentMapper;

    @Override
    public List<SysDepartmentDTO> queryDepartments() {
        //获取企业ID
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //组装条件 , 查询顶级部门
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, companyId);
        wrapper.eq(SysDepartment::getParentId, 0);

        List<SysDepartment> topDepList = departmentMapper.selectList(wrapper);
        List<SysDepartmentDTO> departmentDTOS = BeanHelper.copyWithCollection(topDepList, SysDepartmentDTO.class);

        //查询每一个顶级部门下的子部门 -------> 递归
        queryDepartmentWithChildren(departmentDTOS);

        return departmentDTOS;
    }

    /**
     * 递归查询当前这些部门的子部门
     * @param departmentDTOS
     */
    private void queryDepartmentWithChildren(List<SysDepartmentDTO> departmentDTOS) {
        departmentDTOS.stream().forEach(sysDepartmentDTO -> {

            LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
            wrapper.eq(SysDepartment::getParentId, sysDepartmentDTO.getId());

            List<SysDepartment> childrenDepList = departmentMapper.selectList(wrapper);

            if(CollectionUtil.isNotEmpty(childrenDepList)){
                List<SysDepartmentDTO> childrenDtoList = BeanHelper.copyWithCollection(childrenDepList, SysDepartmentDTO.class);
                sysDepartmentDTO.setChildren(childrenDtoList);

                queryDepartmentWithChildren(childrenDtoList);
            }
        });
    }


    @Override
    public List<Long> queryDepartmentIds() {
        //获取当前企业ID
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //根据企业ID查询所有部门
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, companyId);

        List<SysDepartment> departments = departmentMapper.selectList(wrapper);

        //获取部门ID集合
        List<Long> depIds = departments.stream().map(sysDepartment -> {
            return sysDepartment.getId();
        }).collect(Collectors.toList());

        return depIds;
    }

    @Autowired
    private SysCompanyUserMapper companyUserMapper;

    @Override
    public List<DepartmentOrUserSimpleDTO> querySimleDepartment(Long id, Integer includeMember) {

        List<DepartmentOrUserSimpleDTO> list = new ArrayList<>();

        //组装条件查询员工信息
        if(includeMember == 0){//包含员工
            LambdaQueryWrapper<SysCompanyUser> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            userWrapper.eq(SysCompanyUser::getDepartmentId, id);
            List<SysCompanyUser> sysCompanyUsers = companyUserMapper.selectList(userWrapper);

            if(CollectionUtil.isNotEmpty(sysCompanyUsers)){
                sysCompanyUsers.stream().forEach(sysCompanyUser -> {

                    DepartmentOrUserSimpleDTO simpleUser = new DepartmentOrUserSimpleDTO();
                    simpleUser.setId(sysCompanyUser.getUserId());
                    simpleUser.setName(sysCompanyUser.getUserName());
                    simpleUser.setType(2);

                    list.add(simpleUser);
                });
            }
        }

        //组装查询部门条件
        LambdaQueryWrapper<SysDepartment> depWrapper = new LambdaQueryWrapper<>();
        depWrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        depWrapper.eq(SysDepartment::getParentId, id);

        List<SysDepartment> departments = departmentMapper.selectList(depWrapper);
        if(CollectionUtil.isNotEmpty(departments)){
            departments.stream().forEach(sysDepartment -> {
                DepartmentOrUserSimpleDTO simpleUser = new DepartmentOrUserSimpleDTO();
                simpleUser.setId(sysDepartment.getId());
                simpleUser.setName(sysDepartment.getName());
                simpleUser.setType(1);

                list.add(simpleUser);
            });
        }

        //组装数据并返回
        return list;
    }


    @Override
    public List<Long> queryDepartmentIdsByUserId(Long companyUserId) {

        List<Long> depIds = new ArrayList<>();//

        //查询员工数据, 获取直属部门ID
        SysCompanyUser companyUser = companyUserMapper.selectById(companyUserId);
        if(companyUser != null){
            Long departmentId = companyUser.getDepartmentId();
            depIds.add(departmentId);

            while (true){
                SysDepartment department = departmentMapper.selectById(departmentId);
                Long parentId = department.getParentId();

                if(parentId != null && parentId != 0){
                    depIds.add(parentId);

                    departmentId = parentId;
                }else{
                    break;
                }
            }
        }

        return depIds;
    }
}
